package com.aispeech.task.lasr.event;

import com.aispeech.task.common.data.domain.Task;
import com.aispeech.task.common.data.enums.APICode;
import com.aispeech.task.common.exceptions.TaskException;
import com.aispeech.task.fsm.Event;
import com.aispeech.task.fsm.TerminalEvent;
import com.aispeech.task.lasr.LASREventType;
import com.aispeech.task.lasr.LASRTaskHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
public class FinishEvent extends Event<Task> {
    private List<Map> result;

    public FinishEvent(LASREventType eventType, Task task, List<Map> result) {
        super(eventType, task);
        this.result = result;
    }

    @Override
    public Event fire() {
        Task task = getTarget();

        try {
            Thread.sleep(1000L);
            LASRTaskHandler.taskManager().finishTask(task, result);
        } catch (InterruptedException | TaskException e) {
            log.error("FinishEvent", e);
            try {
                LASRTaskHandler.taskManager().breakTask(task, APICode.INTERNAL_ERROR);
            } catch (TaskException ex) {
                ex.printStackTrace();
            }
        }

        return new TerminalEvent(task);
    }
}
